<template>
  <div class="warehouse-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>仓库管理</h3>
          <div class="header-actions">
            <el-button type="primary" @click="handleAddWarehouse">
              <el-icon><Plus /></el-icon>
              新增仓库
            </el-button>
            <el-button type="primary" @click="refreshData">
              <el-icon><RefreshRight /></el-icon>
              刷新数据
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 仓库列表 -->
      <el-table
        :data="warehouseList"
        border
        stripe
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="仓库名称" min-width="150" />
        <el-table-column prop="location" label="位置" min-width="200" />
        <el-table-column prop="contact" label="联系方式" min-width="150" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="handleViewInventory(scope.row)"
            >
              库存
            </el-button>
            <el-button
              size="small"
              type="warning"
              @click="handleEditWarehouse(scope.row)"
            >
              编辑
            </el-button>
            <el-popconfirm
              title="确定要删除该仓库吗？"
              @confirm="handleDeleteWarehouse(scope.row.id)"
              confirm-button-text="确定"
              cancel-button-text="取消"
            >
              <template #reference>
                <el-button
                  size="small"
                  type="danger"
                >
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 仓库表单弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑仓库' : '新增仓库'"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="warehouseFormRef"
        :model="warehouseForm"
        :rules="warehouseRules"
        label-width="100px"
      >
        <el-form-item label="仓库名称" prop="name">
          <el-input v-model="warehouseForm.name" placeholder="请输入仓库名称" />
        </el-form-item>
        <el-form-item label="位置" prop="location">
          <el-input v-model="warehouseForm.location" placeholder="请输入仓库位置" />
        </el-form-item>
        <el-form-item label="联系方式" prop="contact">
          <el-input v-model="warehouseForm.contact" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="warehouseForm.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input
            v-model="warehouseForm.remarks"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitWarehouse" :loading="submitting">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  Plus, 
  RefreshRight
} from '@element-plus/icons-vue'
import {
  getAllWarehouses,
  getWarehouseById,
  createWarehouse,
  updateWarehouse,
  deleteWarehouse
} from '@/api/inventory'

const router = useRouter()

// 页面数据
const loading = ref(false)
const warehouseList = ref([])

// 表单相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const submitting = ref(false)
const warehouseFormRef = ref(null)

const warehouseForm = reactive({
  id: null,
  name: '',
  location: '',
  contact: '',
  status: 1,
  remarks: ''
})

const warehouseRules = {
  name: [
    { required: true, message: '请输入仓库名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  location: [
    { max: 200, message: '长度不能超过 200 个字符', trigger: 'blur' }
  ],
  contact: [
    { max: 50, message: '长度不能超过 50 个字符', trigger: 'blur' }
  ]
}

// 新增仓库
const handleAddWarehouse = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

// 编辑仓库
const handleEditWarehouse = async (warehouse) => {
  isEdit.value = true
  resetForm()
  
  console.log('编辑前的原始仓库数据:', warehouse)
  
  try {
    loading.value = true
    const response = await getWarehouseById(warehouse.id)
    
    if (response.success) {
      // 获取仓库数据并转换status为表单所需格式
      const warehouseData = response.data
      console.log('后端返回的仓库详情:', warehouseData)
      warehouseData.status = warehouseData.status ? 1 : 0
      console.log('转换status后的仓库数据:', warehouseData)
      Object.assign(warehouseForm, warehouseData)
    } else {
      ElMessage.error(response.message || '获取仓库详情失败')
    }
  } catch (error) {
    console.error('获取仓库详情失败:', error)
    ElMessage.error('获取仓库详情失败')
  } finally {
    loading.value = false
    dialogVisible.value = true
  }
}

// 重置表单
const resetForm = () => {
  if (warehouseFormRef.value) {
    warehouseFormRef.value.resetFields()
  }
  
  warehouseForm.id = null
  warehouseForm.name = ''
  warehouseForm.location = ''
  warehouseForm.contact = ''
  warehouseForm.status = 1
  warehouseForm.remarks = ''
}

// 提交表单
const submitWarehouse = async () => {
  if (!warehouseFormRef.value) return
  
  await warehouseFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      
      try {
        let response
        
        // 准备要提交的数据，确保status是布尔值
        const formData = { ...warehouseForm };
        formData.status = formData.status === 1;
        console.log('提交前的表单数据:', formData)
        
        if (isEdit.value) {
          // 编辑
          response = await updateWarehouse(formData.id, formData)
        } else {
          // 新增
          response = await createWarehouse(formData)
        }
        
        console.log('提交后的响应:', response)
        
        if (response.success) {
          ElMessage.success(isEdit.value ? '更新仓库成功' : '创建仓库成功')
          dialogVisible.value = false
          refreshData()
        } else {
          ElMessage.error(response.message || (isEdit.value ? '更新仓库失败' : '创建仓库失败'))
        }
      } catch (error) {
        console.error(isEdit.value ? '更新仓库失败:' : '创建仓库失败:', error)
        ElMessage.error(isEdit.value ? '更新仓库失败' : '创建仓库失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 删除仓库
const handleDeleteWarehouse = async (id) => {
  try {
    loading.value = true
    const response = await deleteWarehouse(id)
    
    if (response.success) {
      ElMessage.success('删除仓库成功')
      refreshData()
    } else {
      ElMessage.error(response.message || '删除仓库失败')
    }
  } catch (error) {
    console.error('删除仓库失败:', error)
    ElMessage.error('删除仓库失败')
  } finally {
    loading.value = false
  }
}

// 查看仓库库存
const handleViewInventory = (warehouse) => {
  // 跳转到仓库库存详情页
  ElMessage.info('功能即将上线...')
  // 可以在后续开发中实现
  // router.push(`/admin/inventory/warehouse/${warehouse.id}/inventory`)
}

// 刷新数据
const refreshData = async () => {
  loading.value = true
  try {
    const response = await getAllWarehouses()
    
    if (response.success) {
      // 将后端返回的布尔值status转换为前端使用的数字类型(1/0)
      const warehouses = response.data || [];
      warehouses.forEach(warehouse => {
        warehouse.status = warehouse.status === true ? 1 : 0;
      });
      warehouseList.value = warehouses;
      console.log('获取的仓库列表数据:', warehouseList.value)
    } else {
      ElMessage.error(response.message || '获取仓库列表失败')
    }
  } catch (error) {
    console.error('获取仓库列表失败:', error)
    ElMessage.error('获取仓库列表失败')
  } finally {
    loading.value = false
  }
}

// 组件挂载时获取数据
onMounted(() => {
  refreshData()
})
</script>

<style scoped>
.warehouse-management {
  padding-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 10px;
}
</style> 